'use strict';
const BaseService = require('../core/base_service');

class Service extends BaseService {

    async findByCol({findColName, value, model}) {
        return await this.ctx.model[model].findOne({
            where: {
                [findColName]: value
            },
            raw: true
        });
    }

    /**
     * 传入id、model 查询表一条数据
     * @param {Object} object
     * @returns {JSON} Array[Object] 查询的结果
     */
    async findOne({id, model}) {
        return await this.ctx.model[model].findOne({
            where: {
                id
            },
        });
    }

    /**
     * 传入pk、model 查询表一条数据
     * @param {Object} object
     * @returns {JSON} Array[Object] 查询的结果
     */
    async findByPk({id, model}) {
        return await this.ctx.model[model].findByPk(id);
    }

    /**
     * 新增数据 通过查询列判断数据不存在则添加
     * @param {Object} object
     * @returns
     */
    async findCreateFind({findCol, data, model}) {
        let collection = this.ctx.model[model];
        // 注册 添加信息的时候可以用
        let d = {id: this.ctx.helper.getId(), ...data};
        let [rows, isInsert] = await collection.findCreateFind({
            defaults: d,
            where: {[findCol]: data[findCol]},
            raw: true
        });
        console.log('commonService -> insertOrUpdate -> findCreateFind');
        if (isInsert) {
            return rows.id;
        } else {
            return `${findCol} : ${rows[findCol]} is already exists`
        }

    }

    /**
     * 新增和更新数据如果传入id则更新反之新增
     * @param {Object} object
     * @returns
     */
    async insertOrUpdate({data, model}) {

        let collection = this.ctx.model[model];
        if (data.id) {
            console.info('commonService -> insertOrUpdate -> update');
            let result = await collection.update(data, {
                where: {id: data.id}
            })
            console.log(result);
            return result
        } else {
            console.info('commonService -> insertOrUpdate -> create');
            let d = {id: this.ctx.helper.getId(), ...data};
            return await collection.create(d)
        }
    }

    /**
     * 删除数据
     * @param {*} param0
     * @returns
     */
    async delete({id, model}) {
        const result = await this.ctx.model[model].destroy({
            where: {
                id,
            },
        });
        return result === 1 ? `delete success` : `delete failed`
    }


    async pagingQuery(o) {
        let {model, page, limit, queryJson} = o;
        page = isNaN(Number(page)) ? 1 : Number(page);
        limit = isNaN(Number(limit)) ? 10 : Number(limit);
        const Op = this.app.Sequelize.Op;
        let opt = {};
        opt = {
            raw: true,
            offset: (page - 1) * limit, // 当前页
            limit: limit, // 每页显示的条数
            where: {},
        };

        // if (order !== undefined && order !== null && order !== '') {
        //     opt = {
        //         raw: true,
        //         offset: ((page || 1) - 1) * Number(limit || 10), // 当前页
        //         limit: Number(limit || 10), // 每页显示的条数
        //         where: {},
        //         order: order,
        //     };
        // } else {
        //     opt = {
        //         raw: true,
        //         offset: ((page || 1) - 1) * Number(limit || 10), // 当前页
        //         limit: Number(limit || 10), // 每页显示的条数
        //         where: {},
        //     };
        // }
        // sequelize opt


        // 判断queryJson是否存在
        if (queryJson) {
            if (typeof queryJson == 'string') {
                queryJson = JSON.parse(queryJson);
            }

            // 条件查询
            if ('where' in queryJson) {
                let where = queryJson.where;
                let obj = {};
                let count = 0;
                for (const key in where) {
                    if (where[key] !== '') {
                        count++;
                        if (Object.hasOwnProperty.call(where, key)) {
                            obj = {
                                ...obj,
                                ...{
                                    [key]: where[key],
                                },
                            };
                        }
                    }
                }
                console.log(obj);
                // 如果传入都为空则不模糊查询
                if (count === 0) {
                    opt.where = {
                        ...opt.where
                    };
                } else {
                    opt.where = {
                        ...opt.where,
                        ...obj
                    };
                }
            }

            // 模糊查询
            if ('like' in queryJson) {
                let like = queryJson.like;
                let obj = {};
                let count = 0;
                for (const key in like) {
                    if (like[key] !== '') {
                        count++;
                        if (Object.hasOwnProperty.call(like, key)) {
                            obj = {
                                ...obj,
                                ...{
                                    [key]: {
                                        [Op.like]: `%${like[key]}%`,
                                    },
                                },
                            };
                        }
                    }
                }

                // 如果传入都为空则不模糊查询
                if (count === 0) {
                    opt.where = {
                        ...opt.where
                    };
                } else {
                    opt.where = {
                        ...opt.where,
                        ...{
                            [Op.or]: obj
                        }
                    };
                }
            }
        }
        console.log(opt);

        return await this.ctx.model[model].findAndCountAll(opt);
    }


}

module.exports = Service;
